<?php
class System_UserController extends Zend_Controller_Action {
    //Phuong thuc init()
    public function init() {
        $app = Zend_Registry::get('App');
        $this->view->baseUrl = $baseUrl = $this->_request->getBaseUrl() . "/public/";
        $result = array(
                    array($baseUrl.'lib-js/system/admin/System_Admin_User.js','js')
                    ,array($baseUrl.'lib-js/system/jsTree/_lib/jquery.cookie.js','js')
                    ,array($baseUrl.'lib-js/system/jsTree/_lib/jquery.hotkeys.js','js')
                    ,array($baseUrl.'lib-js/system/jsTree/jquery.jstree.js','js')
                    ,array($baseUrl.'lib-js/system/admin/Tree.js','js')
                    ,array($baseUrl.'lib-js/jquery.lightbox_me.js','js')
                    ,array($baseUrl.'lib-js/ui/jquery.ui.datepicker-vi.js','js')
                    ,array($baseUrl.'css/popup.css','css')
                    ,array($baseUrl.'css/user.css','css')
                    ,array($baseUrl.'css/themes/blitzer/jquery-ui-1.8.14.custom.css','css')
                    ,array($baseUrl.'css/themes/base/calendar.css','css')
                );
        if ($this->_request->isXmlHttpRequest()){
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'partial'
            ));
            $this->view->arrJsCss = Zend_Json::encode($result);
        }else{
            //Cau hinh cho Zend_layout
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'index'
            ));
            $response = $this->getResponse();
            
            $this->view->currentModulCode = "SYSTEM";
            $this->view->currentModulCodeForLeft = "user";
            $this->view->postHeader = Clound_String::registerFile($result);

            //Hien thi file template
            $response->insert('menu', $this->view->renderLayout('menu.phtml', './application/layout/scripts/'));     //Hien thi header 
            $response->insert('submenu', $this->view->renderLayout('submenu.phtml', './application/layout/scripts/'));     //Hien thi header 
            $response->insert('footer', $this->view->renderLayout('footer.phtml', './application/layout/scripts/'));   //Hien thi f
        }

    }

    public function indexAction() {
		//var_dump($_SESSION);
        //$cacheFile = new Clound_CacheFile();
        //$cache = $cacheFile->getList('DM12');
        //var_dump($cache);
    }
    public function getChildNode($idNode,$arrTreeGetAll,$sType){
        $arrOutput = array();
        if($idNode==''){
            $rel ='home';
            $class = 'home';
        }else{
            $rel ='folder7';
            $class = 'unit';
        }
        foreach ($arrTreeGetAll as $key => $value) {
            if($value['UnitParent'] == $idNode){
				//var_dump($value);
                array_push($arrOutput, array('attr'=>array(
                                                'id'=>$value['UnitID']
                                                ,'rel'=>$rel
                                                ,'class'=>$class
                                            ),
                                            'data'=>$value['Name'],
                                            'state'=>'closed'
                ));
            }
        }
		//exit;
        $arrStaff = Clound_Session::getInstance()->get('StaffAll');
        foreach ($arrStaff as $key => $value) {
            if($value['UnitID'] == $idNode){
                array_push($arrOutput, array('attr'=>array(
                                                'id'=>$value['StaffID']
                                                ,'rel'=>'user'
                                                ,'class'=>'staff'
                                            ),
                                            'data'=>$value['Name'],
                                            // 'state'=>'closed'
                ));
            }
        }
        return $arrOutput;
    }
    public function loadtreeAction(){
        $Unit = new System_Models_Unit();
        $Staff = new System_Models_Staff();
        $session = new Clound_Session();
        $arrTree = '';
        $idNode = $this->_request->getParam('id','');
        $sType = $this->_request->getParam('sType','');


        $arrTreeGetAll = $session->get('UnitAll');
        if(!$arrTreeGetAll) {
            $arrTreeGetAll = $Unit->getAllTree();
            $session->set('UnitAll',$arrTreeGetAll);

        }
        if(!$session->get('StaffAll')) {
            $session->set('StaffAll',$Staff->getAllTree());
        }

        $arrTree = $this->getChildNode($idNode,$arrTreeGetAll,$sType);
        echo json_encode($arrTree);
        die;
    }
   public function addAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
        $act = $this->_request->getParam('act','');
        if ($act == 'add') $id = '';
        if ($act == 'edit') $id = $this->_request->getParam('idNode','');
        $idNode = $this->_request->getParam('idNode','');
        $nameNode = $this->_request->getParam('nameNode','');
        // echo  $idNode.$nameNode ;die();
        //Gan gia tri mac dinh cho cac Input
        $modelUnit = new System_Models_Unit();
        $model = $modelUnit->selectRow($id,$idNode,$nameNode);
        $this->view->act = $act;
        $this->view->model = $model;
        $this->view->UnitParent = $model['UnitParent'];
    }
    public function saveAction() {
        // Tao doi tuong modeListType
        $model = new System_Models_Unit();
        //Lay cac tham so cua form
        $act = $this->_request->getParam('act','');
        $sCode = trim(htmlspecialchars($this->_request->getParam('Code')));
        $sName = trim(htmlspecialchars($this->_request->getParam('Name')));
        $Orders = trim($this->_request->getParam('Orders'));
        $id = (int) $this->_request->getParam('UnitID');
        $UnitParent = (int) $this->_request->getParam('UnitParent');
        $selectTree = (int) $this->_request->getParam('selectTree');
        $ownerCode = $this->_request->getParam('OwnerCode');
        $Address = $this->_request->getParam('Address');
        $Tel = $this->_request->getParam('Tel');
        $Email = $this->_request->getParam('Email');
        $OwnerCode = $this->_request->getParam('OwnerCode');
        $status = $this->_request->getParam('Status');
        // echo $UnitParent;die();
        $arrUnit = Clound_Session::getInstance()->get('UnitAll');
        $data = array(
                "UnitID"=> $id,
                'UnitParent' => $selectTree,
                "Code"=> $sCode,
                "Name"=> $sName,
                "Tel"=> $Tel,
                "Address"=> $Address,
                "Email"=> $Email,
                "Orders"=> $Orders,
                "OwnerCode"=>$OwnerCode,
                "Status"=>$status,
            );
        if ($act == 'add') {            
            $data['UnitID'] = null;
            $model->insert($data);
            $result = $model->getAdapter()->lastInsertId();
            $data['UnitID'] = $result;
            array_push($arrUnit,$data);
            Clound_Session::getInstance()->set('UnitAll',$arrUnit);
            // $sql = "call updatePositionNode($UnitParent,$result)";
            // $model->getDefaultAdapter()->fetchRow($sql);
        } else if ($act == 'edit') {
            $model->update($data,"UnitID ='$id'");
            $iMax = sizeof($arrUnit);
            for ($i=0; $i < $iMax; $i++) { 
                if ($arrUnit[$i]['UnitID'] == $id) {
                    $arrUnit[$i] = $data;
                    Clound_Session::getInstance()->set('UnitAll',$arrUnit);
                    break;
                }
            }
        }
        die;
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }
    public function deleteAction() {

        $model = new System_Models_Unit();
        $nodeList = $this->_request->getParam('nodeList');
        // $nodeList = str_replace(",", "','",  $nodeList);
        // $nodeList = "'$nodeList'";
        $result = array();
        $arrNodeID = explode(',', $nodeList);
        $arrNodeID = $model->getIDAllowDelete($arrNodeID);
        $result = $model->deleteRows($arrNodeID);
        $error = '';
        if($result){
            $arrUnit = Clound_Session::getInstance()->get('UnitAll');
            foreach ($arrNodeID as $key => $id) {
                foreach ($arrUnit as $key => $unit) {
                    if ($unit['UnitID'] == $id) {
                        unset($arrUnit[$key]);
                        break;
                    }
                }
            }
            Clound_Session::getInstance()->set('UnitAll',$arrUnit);
        }else{
            $error ='Bạn kiểm tra xóa các phòng ban/ cán bộ thuộc phòng này!';
        }
        
        echo $error;
        die();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }

    public function addstaffAction(){
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
        $cacheFile = new Clound_CacheFile();
        $DM15 = $cacheFile->getList('DM15');
        $DM14 = $cacheFile->getList('DM14');
		//var_dump($DM14);exit;
        $act = $this->_request->getParam('act','');
        if ($act == 'addstaff') $id = '';
        if ($act == 'editstaff') $id = $this->_request->getParam('idNode','');
        // echo $id;die();
        $idNode = $this->_request->getParam('idNode','');
        $nameNode = $this->_request->getParam('nameNode','');
        // echo  $idNode.$nameNode ;die();
        //Gan gia tri mac dinh cho cac Input
        $Staff = new System_Models_Staff();
        $model = $Staff->selectRow($id,$idNode,$nameNode);
        // var_dump($model);die();
        $this->view->act = $act;
        $this->view->model = $model;
        $this->view->UnitParent = $model['UnitID'];
        $this->view->DM15 = $DM15;
        $this->view->DM14 = $DM14;
    }
    public function savestaffAction() {
        // Tao doi tuong modeListType
        $model = new System_Models_Staff();
        //Lay cac tham so cua form
        $act    = $this->_request->getParam('act','');
        $sName  = trim(htmlspecialchars($this->_request->getParam('Name')));
        $Orders = trim($this->_request->getParam('Orders'));
        $id     = (int) $this->_request->getParam('StaffID');
        $idNode = (int) $this->_request->getParam('idNode');
        $nameNode   = ($this->_request->getParam('parentUnit'));
        $ownerCode  = $this->_request->getParam('ownerCode');
        $Address    = $this->_request->getParam('Address');
        $Mobile = $this->_request->getParam('Mobile');
        $Email  = $this->_request->getParam('Email');
        $sSex   = $this->_request->getParam('Sex');
        $Username = $this->_request->getParam('Username');
        $Password = $this->_request->getParam('Password');
        $PositionCode = $this->_request->getParam('PositionCode');
        $Status     = $this->_request->getParam('Status');
        $Birthday   = Clound_Datetime::getInstance()->convertDateTime($this->_request->getParam('Birthday'));
        $UnitParent = (int) $this->_request->getParam('UnitParent');
        $selectTree = (int) $this->_request->getParam('selectTree');
        $data = array(
                "Name"      => $sName,
                "Sex"       => $sSex,
                "Username"  => $Username,
                "Address"   => $Address,
                "Birthday"  => $Birthday,
                "Mobile"    => $Mobile,
                "Email"     => $Email,
                "Orders"    => $Orders,
                "Status"    => $Status,
                "PositionCode"    => $PositionCode,
            );
        if ($selectTree != '')
                $UnitParent =  $selectTree;
        else $UnitParent = $UnitParent;
        if ($act == 'addstaff'){
            $data['StaffID']    = null;
            $data['UnitID']     = $idNode;
            $data['Password']   = md5($Password);
        }elseif ($act == 'editstaff') {
                $id = $idNode;
                $data['StaffID']    = $id;
                $data['UnitID']     = $UnitParent;
                if ($Password) {
                    $data['Password']   = md5($Password);
                }
        }
        $arrStaff = Clound_Session::getInstance()->get('StaffAll');
        if ($id === 0) {
            try {
                $model->insert($data);
                $result = $model->getAdapter()->lastInsertId();
            } catch (Exception $e) { echo $e->getMessage();}
            $data['StaffID'] = $result;
            array_push($arrStaff,$data);
            Clound_Session::getInstance()->set('StaffAll',$arrStaff);
            echo $result;
        } else {
            $where="StaffID ='$id'";
            $model->update($data,$where);
            $iMax = sizeof($arrStaff);
            for ($i=0; $i < $iMax; $i++) { 
                if ($arrStaff[$i]['StaffID'] == $id) {
                    $arrStaff[$i] = $data;
                    Clound_Session::getInstance()->set('StaffAll',$arrStaff);
                    break;
                }
            }
        }
        die;
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }
    public function checkuserAction() {
        $model = new System_Models_Staff();
        $username = $this->_request->getParam('username');
        echo $model->checkexit($username); 
        die;
    }
    public function deletestaffAction() {
        $model = new System_Models_Staff();
        $nodeList = $this->_request->getParam('nodeList');
        $arrNodeID = explode(',', $nodeList);
        $where = $model->getAdapter()->quoteInto("StaffID IN (?)", $arrNodeID);
        $error = '';
        if($model->delete($where)) {
            $arrStaff = Clound_Session::getInstance()->get('StaffAll');
            foreach ($arrNodeID as $key => $id) {
                foreach ($arrStaff as $key => $staff) {
                    if ($staff['StaffID'] == $id) {
                        unset($arrStaff[$key]);
                        break;
                    }
                }
            }
            Clound_Session::getInstance()->set('StaffAll',$arrStaff);
        }else {
            $error = 'Có lỗi xảy ra!';
        }
        echo $error; die();
    }
    public function changepassAction() {
        $model = new System_Models_Staff();
        $nodeList = $this->_request->getParam('nodeList');
        $where="StaffID ='$nodeList'";
        $result = $model->update(array("Password"=> md5('123456')),$where);
        echo $result;
        die();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }

    public function refreshAction(){
        $modelUnit = new System_Models_Unit();
        $modelStaff = new System_Models_Staff();
        $session = new Clound_Session();
        try {
            $session->set('StaffAll',$modelStaff->getAllTree());
            $session->set('UnitAll',$modelUnit->getAllTree());
            
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        die;
    }
}
?>